package com.biquge.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.biquge.dao.NovelDao;
import com.biquge.entity.Novel;
import com.biquge.service.NovelService;
import com.biquge.service.novelReptile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;

/**
 * @author wangmeng
 * @since 2021/12/11
 */
@Controller
@RequestMapping()
public class NovelController {


    @Autowired
    NovelDao novelDao;
    @Autowired
    NovelService novelService;

    @GetMapping
    public String list(Model model) {
        List<Novel> novelList = novelDao.selectList(new LambdaQueryWrapper<>());
        model.addAttribute("list", novelList);
        return "index";
    }


    @GetMapping("start-download")
    @ResponseBody
    public String startDownload(String url) {
        novelService.startDownload(url);
        return "请求成功，小说正在极速获取";
    }


    @GetMapping("download")
    @ResponseBody
    public String download(Integer novelId, HttpServletResponse response) {
        Novel novel = novelDao.selectById(novelId);
        File file = new File(novelReptile.dirPath + File.separator + novel.getNovelName() + File.separator + novel.getNovelName() + ".txt");
        String fileName = novel.getNovelName();
        resetResponse(response, fileName + ".txt");
        //4.获取要下载的文件输入流
        try (InputStream in = new FileInputStream(file)) {
            int len = 0;
            //5.创建数据缓冲区
            byte[] buffer = new byte[1024];
            //6.通过response对象获取OutputStream流
            OutputStream out = response.getOutputStream();
            //7.将FileInputStream流写入到buffer缓冲区
            while ((len = in.read(buffer)) > 0) {
                //8.使用OutputStream将缓冲区的数据输出到客户端浏览器
                out.write(buffer, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "download";
    }

    public static void resetResponse(HttpServletResponse response, String fileName) {
        try {
            fileName = URLEncoder.encode(fileName, "UTF-8");
            fileName = fileName.replace("+", "%20");
            fileName = fileName.replace("%24", "$");
            String gb2312 = new String(fileName.getBytes("gb2312"), "ISO8859-1");
            response.reset();
            response.addHeader("Access-Control-Allow-Origin", "*");
            response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
            response.setContentType("application/octet-stream; charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + gb2312);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }
}
